<template>
  <div class="container">
    <div class="apply-container">
      <div class="apply-container-head"></div>
      <div class="apply-container-body">
        <div class="apply-container-body-title">
          <div class="apply-container-body-title-font">用车申请综合办审批</div>
          <div class="apply-container-body-title-return">
            <el-button size="small" @click="goBackPage">返回</el-button>
          </div>
        </div>
        <el-divider class="apply-container-body-title-line"></el-divider>
        <div class="model-title">申请信息</div>
        <div class="apply-container-body-content">
          <el-form :model="AutoOrder" label-width="100px" label-position="LabelPosition" disabled style="width: 100%;">
            <el-form-item label="用车部门:" prop="userDepartment" style="width: 40%;">
              <el-select v-model="AutoOrder.userDepartment" placeholder="请选择用车部门" clearable></el-select>
            </el-form-item>
            <el-form-item label="姓名:" prop="userName" style="width: 40%;">
              <el-input v-model="AutoOrder.userName" placeholder="请输入姓名" clearable></el-input>
            </el-form-item>
            <el-form-item label="工号:" prop="userId" style="width: 40%;">
              <el-input v-model="AutoOrder.userId" placeholder="请输入工号" clearable></el-input>
            </el-form-item>
            <el-form-item label="申请人电话:" prop="userPhone" style="width: 40%;">
              <el-input v-model="AutoOrder.userPhone" placeholder="请输入申请人电话" clearable></el-input>
            </el-form-item>
            <el-form-item label="车型:" prop="autoType" style="width: 40%;">
              <el-select v-model="AutoOrder.autoType" placeholder="请选择车型" clearable></el-select>
            </el-form-item>
            <el-form-item label="成员数:" prop="passengerNum" style="width: 40%;">
              <el-input v-model="AutoOrder.passengerNum" placeholder="请输入成员数" clearable></el-input>
            </el-form-item>
            <el-form-item label="取车时间:" prop="autoStartTime" style="width: 40%;">
              <el-date-picker v-model="AutoOrder.autoStartTime" type="datetime" value-format="yyyy-MM-dd-HH-mm"
                placeholder="请选择日期时间" clearable></el-date-picker>
            </el-form-item>
            <el-form-item label="截止时间:" prop="autoArriveTime" style="width: 40%;">
              <el-date-picker v-model="AutoOrder.autoArriveTime" type="datetime" value-format="yyyy-MM-dd-HH-mm"
                placeholder="请选择日期时间" clearable></el-date-picker>
            </el-form-item>
            <el-form-item label="目的地:" prop="userDestination" style="width: 50%;">
              <el-input v-model="AutoOrder.userDestination" placeholder="请输入目的地" clearable></el-input>
            </el-form-item>
            <el-form-item label="用车事由:" prop="autoUseReason" style="width: 50%;">
              <el-input v-model="AutoOrder.autoUseReason" type="textarea" placeholder="请输入内容" maxlength="100"
                show-word-limit></el-input>
            </el-form-item>
          </el-form>
        </div>
        <el-divider class="apply-container-body-title-line"></el-divider>
        <div class="model-title">审批意见</div>
        <div class="apply-container-body-approval">
          <el-form :model="Approval" label-width="125px" label-position="LabelPosition" ref="Approval"
            :rules="ApprovalRules" style="width: 100%;">
            <el-form-item label="审批人:" prop="OrderApprover" style="width: 20%;">
              <el-radio-group v-model="Approval.OrderApprover">
                <el-radio :label="GeneralOrderApprover"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="审批意见:" prop="ApprovalResult" style="width: 40%;">
              <el-radio-group v-model="Approval.ApprovalResult">
                <el-radio label="同意"></el-radio>
                <el-radio label="不同意"></el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="审批备注:" prop="ApprovalDescribe" style="width: 55%;">
              <el-input v-model="Approval.ApprovalDescribe" type="textarea" placeholder="请输入内容" maxlength="100"
                show-word-limit></el-input>
            </el-form-item>
            <el-form-item label="分配车辆车牌号:" prop="SelectAutoPlateNum" style="width: 40%;">
              <el-select v-model="Approval.SelectAutoPlateNum" placeholder="请选择车牌号" clearable>
                <el-option v-for="item in Approval.SelectAutoPlateNumOptions" :key="item.autoId"
                  :label="item.autoPlateNum" :value="item.autoPlateNum"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="分配驾驶员:" prop="SelectDriverId" style="width: 40%;">
              <el-select v-model="Approval.SelectDriverId" placeholder="请选择驾驶员" @change="SetDNAndDP" clearable>
                <el-option v-for="item in Approval.SelectDriverIdOptions" :key="item.userId"
                  :label="renderOptionLabel(item.userId, item.driverName)" :value="deepCopy(item)"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="驾驶员姓名:" prop="InputDriverName" style="width: 50%;">
              <el-input v-model="Approval.InputDriverName" placeholder="请先选择驾驶员" disabled clearable></el-input>
            </el-form-item>
            <el-form-item label="驾驶员电话:" prop="InputDriverPhone" style="width: 50%;">
              <el-input v-model="Approval.InputDriverPhone" placeholder="请先选择驾驶员" disabled clearable></el-input>
            </el-form-item>
            <div class="apply-container-body-content-submit">
              <el-button type="primary" @click="Submit('Approval')">提交</el-button>
            </div>
          </el-form>
        </div>
      </div>
      <div class="apply-container-footer"></div>
    </div>
  </div>
</template>
  
<script>
import { getAutoOrderById } from '@/api/approval.js'
import { queryFreePlateNum } from '@/api/approval.js'
import { queryFreeDrivers } from '@/api/approval.js'
import { addAutoGeneralApproval } from '@/api/approval.js'
import { updateAutoOrderProgress } from '@/api/application.js'
import { updateTodoStatus } from '@/api/todo.js';
import { insertTodo } from '@/api/todo.js';
export default {
  name: 'AutoDepartmentApprovalView',
  data() {
    return {
      LabelPosition: 'right',
      AutoOrder: {
        userDepartment: null,
        userName: null,
        userId: null,
        userPhone: null,
        autoType: null,
        passengerNum: null,
        autoStartTime: null,
        autoArriveTime: null,
        userDestination: null,
        autoUseReason: null,
      },
      Approval: {
        OrderApprover: null,
        ApprovalResult: null,
        ApprovalDescribe: null,
        SelectAutoPlateNum: null,
        SelectAutoPlateNumOptions: [],
        SelectDriverId: null,
        SelectDriverIdOptions: [],
        InputDriverPhone: null,
        InputDriverName: null, //展示使用，不传到后端
      },
      ApprovalRules: {
        OrderApprover: [{ required: true, message: '请选择审批人', trigger: 'change' },],
        ApprovalResult: [{ required: true, message: '请选择审批意见', trigger: 'change' },],
        SelectAutoPlateNum: [{ required: true, message: '请选择车牌号', trigger: 'change' },],
        SelectDriverId: [{ required: true, message: '请选择驾驶员', trigger: 'change' },],
        InputDriverPhone: [{ required: true, message: '请输入驾驶员电话', trigger: 'blur' },],
        InputDriverName: [{ required: true, message: '请输入驾驶员姓名', trigger: 'blur' },],
      },
      SubmitApproval: {
        orderId: null,
        orderApprover: null,
        approvalResult: null,
        approvalDescribe: null,
        userId: null,
        submitTime: null,
        autoPlateNum: null,
        driverId: null,
        driverPhone: null,
      },
      SubmitAutoUserTodo: {
        userId: null,
        todoTime: null,
        todoType: null,
        orderId: null,
        todoStatus: null,
      },
      SubmitDriverTodo: {
        userId: null,
        todoTime: null,
        todoType: null,
        orderId: null,
        todoStatus: null,
      },
      SubmitTime: null,
      GeneralOrderApprover: null,
      AutoOrderId: null, //待办转入
      UserId: null,
      AutoOrderProgress: 3,
      TodoType: '用车申请综合办审批',
      SubmitCode: [],
    }
  },

  methods: {
    deepCopy(obj) {
      return JSON.stringify(obj); //转化为字符串
    },
    SetDNAndDP(newValue) {
      if (newValue === '') {
        this.Approval.InputDriverPhone = null;
        this.Approval.InputDriverName = null;
      } else {
        let temp = JSON.parse(newValue); //将字符串解密
        this.Approval.InputDriverPhone = temp.driverPhone;
        this.Approval.InputDriverName = temp.driverName;
      }
    },
    renderOptionLabel(userId, driverName) {
      return userId + "（" + driverName + "）";
    },
    UpdateCurrentTime() {
      const currentDateTime = new Date();
      const dateOptions = { year: 'numeric', month: '2-digit', day: '2-digit' };
      const timeOptions = { hour: '2-digit', minute: '2-digit', second: '2-digit' };
      const formattedDate = currentDateTime.toLocaleDateString(undefined, dateOptions);
      const formattedTime = currentDateTime.toLocaleTimeString(undefined, timeOptions);
      this.SubmitTime = `${formattedDate} ${formattedTime}`;
    },
    GetAutoOrderById() {
      return new Promise((resolve, reject) => {
        getAutoOrderById(this.AutoOrderId)
          .then(res => {
            const temp = res.data.data;
            this.AutoOrder = temp;
            if (res.data.code === '0') {
              console.log(res.data.code);
              resolve(); // 表示异步操作成功
            } else {
              console.log(res.data.msg);
              reject(res.data.msg); // 表示异步操作失败
            }
          })
          .catch(err => {
            console.log(err);
            reject(err); // 处理异步错误
          })
      });
    },
    QueryFreePlateNum() {
      return new Promise((resolve, reject) => {
        queryFreePlateNum(this.AutoOrder.autoType).then(res => {
          this.Approval.SelectAutoPlateNumOptions = res.data.data;
          if (res.data.code === '0') {
            console.log(res.data.code);
            resolve(); // 表示异步操作成功
          } else {
            console.log(res.data.msg);
            reject(res.data.msg); // 表示异步操作失败
          }
        })
          .catch(err => {
            console.log(err);
            reject(err); // 处理异步错误
          })
      });
    },
    QueryFreeDrivers() {
      return new Promise((resolve, reject) => {
        queryFreeDrivers().then(res => {
          this.Approval.SelectDriverIdOptions = res.data.data;
          if (res.data.code === '0') {
            console.log(res.data.code);
            resolve(); // 表示异步操作成功
          } else {
            console.log(res.data.msg);
            reject(res.data.msg); // 表示异步操作失败
          }
        })
          .catch(err => {
            console.log(err);
            reject(err); // 处理异步错误
          })
      });
    },
    AddAutoGeneralApproval() {
      return new Promise((resolve, reject) => {
        this.SubmitApproval.orderId = this.AutoOrderId;
        this.SubmitApproval.orderApprover = this.Approval.OrderApprover;
        this.SubmitApproval.approvalResult = this.Approval.ApprovalResult;
        this.SubmitApproval.approvalDescribe = this.Approval.ApprovalDescribe;
        this.SubmitApproval.userId = this.UserId;
        this.SubmitApproval.submitTime = this.SubmitTime;
        this.SubmitApproval.autoPlateNum = this.Approval.SelectAutoPlateNum;
        this.SubmitApproval.driverId = JSON.parse(this.Approval.SelectDriverId).userId;
        this.SubmitApproval.driverPhone = this.Approval.InputDriverPhone;
        console.log(this.SubmitApproval);
        addAutoGeneralApproval(this.SubmitApproval)
          .then(res => {
            this.SubmitCode.push(res.data.code);
            if (res.data.code === '0') {
              console.log(res.data.code);
              resolve(); // 表示异步操作成功
            } else {
              console.log(res.data.msg);
              reject(res.data.msg); // 表示异步操作失败
            }
          })
          .catch(err => {
            console.log(err);
            reject(err); // 处理异步错误
          });
      });
    },
    UpdateAutoOrderProgress() {
      return new Promise((resolve, reject) => {
        updateAutoOrderProgress(this.AutoOrderId, this.AutoOrderProgress)
          .then(res => {
            this.SubmitCode.push(res.data.code);
            if (res.data.code === '0') {
              console.log(res.data.code);
              resolve(); // 表示异步操作成功
            } else {
              console.log(res.data.msg);
              reject(res.data.msg); // 表示异步操作失败
            }
          })
          .catch(err => {
            console.log(err);
            reject(err); // 处理异步错误
          });
      });
    },
    UpdateTodoStatus() {
      return new Promise((resolve, reject) => {
        updateTodoStatus(this.TodoType, this.AutoOrderId)
          .then(res => {
            this.SubmitCode.push(res.data.code);
            if (res.data.code === '0') {
              console.log(res.data.code);
              resolve(); // 表示异步操作成功
            } else {
              console.log(res.data.msg);
              reject(res.data.msg); // 表示异步操作失败
            }
          })
          .catch(err => {
            console.log(err);
            reject(err); // 处理异步错误
          });
      });
    },
    AddAutoUserTodo() {
      return new Promise((resolve, reject) => {
        this.SubmitAutoUserTodo.userId = this.AutoOrder.userId;
        this.SubmitAutoUserTodo.todoTime = this.SubmitTime;
        this.SubmitAutoUserTodo.todoType = "用车通知";
        this.SubmitAutoUserTodo.orderId = this.AutoOrderId;
        this.SubmitAutoUserTodo.todoStatus = '未完成';
        insertTodo(this.SubmitAutoUserTodo)
          .then(res => {
            this.SubmitCode.push(res.data.code);
            if (res.data.code === '0') {
              console.log(res.data.code);
              resolve(); // 表示异步操作成功
            } else {
              console.log(res.data.msg);
              reject(res.data.msg); // 表示异步操作失败
            }
          })
          .catch(err => {
            console.log(err);
            reject(err); // 处理异步错误
          });
      });
    },
    AddDriverTodo() {
      return new Promise((resolve, reject) => {
        this.SubmitDriverTodo.userId = JSON.parse(this.Approval.SelectDriverId).userId;
        this.SubmitDriverTodo.todoTime = this.SubmitTime;
        this.SubmitDriverTodo.todoType = "用车委派";
        this.SubmitDriverTodo.orderId = this.AutoOrderId;
        this.SubmitDriverTodo.todoStatus = '未完成';
        insertTodo(this.SubmitDriverTodo)
          .then(res => {
            this.SubmitCode.push(res.data.code);
            if (res.data.code === '0') {
              console.log(res.data.code);
              resolve(); // 表示异步操作成功
            } else {
              console.log(res.data.msg);
              reject(res.data.msg); // 表示异步操作失败
            }
          })
          .catch(err => {
            console.log(err);
            reject(err); // 处理异步错误
          });
      });
    },
    //检错，可复用
    JudgeSubmitCode(data) {
      const allZeros = data.every(code => code === '0');
      return allZeros;
    },
    showMessage(message, type) {
      this.$message({
        message: message,
        duration: 2000,
        showClose: true,
        type: type,
      });
    },
    goBackPage() {
      this.$router.go(-1)
    },
    JudgeSuccess(data) {
      if (this.JudgeSubmitCode(data)) {
        this.showMessage('审批成功!', 'success');
        this.goBackPage();
      } else
        this.showMessage('审批失败!', 'error');
    },
    Submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$confirm('此操作将审批该用车工单, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.UpdateCurrentTime();
            this.AddAutoGeneralApproval()
              .then(() => this.UpdateAutoOrderProgress())
              .then(() => this.UpdateTodoStatus())
              .then(() => this.AddAutoUserTodo())
              .then(() => this.AddDriverTodo())
              .then(() => this.JudgeSuccess(this.SubmitCode))
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
        }
        else {
          return false;
        }
      })
    },
    InitData() {
      return new Promise((resolve, reject) => {
        try {
          this.GeneralOrderApprover = localStorage.getItem('userName')
          this.UserId = localStorage.getItem('userId');
          this.AutoOrderId = this.$route.query.OrderId;
          resolve(); // 表示异步操作成功
        } catch (error) {
          console.log(error);
          reject(error); // 处理异步错误
        }
      });
    },
  },

  created() {
    this.InitData()
      .then(() => this.GetAutoOrderById())
      .then(() => this.QueryFreePlateNum())
      .then(() => this.QueryFreeDrivers())
  },
}
</script>
  
<style scoped>
.container {
  /* height: 100%; */
  width: 95%;
  margin: 0 auto;
  background-color: #ffffff;
  margin-top: 1%;
}

.apply-container {
  width: 90%;
  height: 100%;
  margin: 0 auto;

}

.apply-container-head {
  width: 95%;
  height: 30px;
  margin: 0 auto;
}

.apply-container-body {
  width: 95%;
  height: 92%;
  margin: 0 auto;
  background-color: #ffffff;

}

.apply-container-body-title {
  width: 98%;
  height: 5%;
  margin: 0 auto;
  display: flex;
}

.apply-container-body-title-return {
  width: 100%;
  padding-top: 5px;
  display: flex;
  justify-content: flex-end;
}

.apply-container-body-title-line {
  height: 1px;
  width: 98%;
  margin: 5px auto;
}

.apply-container-body-title-font {
  width: 100%;
  height: 99%;
  font-size: 18px;
  font-weight: bold;
  text-align: left;
  padding-top: 10px;
}

.apply-container-body-content {
  width: 85%;
  height: 60%;
  margin: 20px auto;
  display: flex;

}

.apply-container-body-content-submit {
  width: 100%;
  height: 40px;
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.apply-container-body-approval {
  width: 85%;
  height: 40%;
  margin: 20px auto;
  display: flex;

}

.apply-container-footer {
  width: 95%;
  height: 10px;
  margin: 0 auto;
}

.model-title {
  font-weight: bold;
}
</style>